package com.cskaoyan.utils;

import org.apache.commons.lang.StringUtils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

/**
 * Description
 *
 * @author Zhangfei tangjian
 * @date Created on 2021/10/21
 */
public class CouponPastInformUtil {

    private static final Integer CodeInvalidTimeSeconds = 5*60;
    private static final Integer CodeSendIntervalTimeSeconds = 60;
    /**
     * 正则表达式：验证手机号
     */
    public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    /**
     * 正则表达式：验证邮箱
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    public static boolean checkEmail(String email){
        return Pattern.matches(REGEX_EMAIL,email);
    }
    public static boolean checkPhone(String phone){
        return Pattern.matches(REGEX_MOBILE,phone);
    }

    public static String getRandomCode(String phoneOrMail,ServletContext session){

        String code = (String) session.getAttribute(phoneOrMail);
        if (code == null) return "";
        return code;
    }

    public static String sendRandomCode(String phoneOrMail, ServletContext session){
        String code = "false";
        boolean sendStatus = false;

        String times = (String) session.getAttribute("times");
        if (StringUtils.isNotEmpty(times) && "0".equals(times)){
            return "一分钟后再获取";
        }

        try {
            if (checkEmail(phoneOrMail)){
                code = sendMailRandomCode(phoneOrMail);
            }
            if (checkPhone(phoneOrMail)){
                code = sendPhoneRandomCode(phoneOrMail);
            }

            sendStatus = true;
        }catch (Exception e){
            e.printStackTrace();
            return "系统维护,请稍后再试!";
        }

        session.setAttribute("times","0");
        session.setAttribute(phoneOrMail,code);


        final Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String code = (String) session.getAttribute(phoneOrMail);
                if(StringUtils.isNotEmpty(code)){
                    session.removeAttribute(phoneOrMail);
                }
                timer.cancel();
            }
        },CodeInvalidTimeSeconds*1000);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String code = (String) session.getAttribute("times");
                if(StringUtils.isNotEmpty(code)){
                    String times = (String) session.getAttribute("times");
                    session.setAttribute("times","1");
                }
                timer.cancel();
            }
        },CodeSendIntervalTimeSeconds*1000);



        return "success";
    }


    public static String sendPhoneRandomCode(String phone){
        String code = PhoneSendSms.sendSms(phone);

        return code;
    }

    public static String sendMailRandomCode(String mail){
        // 创建Properties 类用于记录邮箱的一些属性
        Properties props = new Properties();
        // 表示SMTP发送邮件，必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", "smtp.qq.com");
        //端口号，QQ邮箱端口587
        props.put("mail.smtp.port", "587");
        // 此处填写，写信人的账号
        props.put("mail.user", "pan8494@qq.com");
        // 此处填写16位STMP口令
        props.put("mail.password", "qayimpuuqgimbbdh");

        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = null;
        //验证码
        // String code = RandomUtil.GetRandomString(6);
        try {
            form = new InternetAddress(props.getProperty("mail.user"));
            message.setFrom(form);

            // 设置收件人的邮箱
            InternetAddress to = new InternetAddress(mail);
            message.setRecipient(MimeMessage.RecipientType.TO, to);

            // 设置邮件标题
            message.setSubject("CS商城通知");

            //把验证码放入redis
//            RedisUtil redisUtil = new RedisUtil();
//            redisUtil.setex(mail, 60, code);

            // 设置邮件的内容体
            message.setContent("【CS商城】:尊敬的用户你有优惠卷快过期了，尽快登录购物吧！", "text/html;charset=UTF-8");

            // 最后当然就是发送邮件
            Transport.send(message);


        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        return "wangdao";
    }


}
